/****************************************************************
 * <strong>MFActionFilter管理类</strong>
 *
 * <p>
 * MFActionFilter管理类
 * </p>
 *
 * @author AndyZhang 2011
 * @version 0.1
 * ToDo:2011-12-29
 ***************************************************************/

package com.thinkwide.data.filter;

import com.thinkwide.data.mvc.action.MFActionManager;
import com.thinkwide.data.core.MFPath;
import com.thinkwide.data.debug.MFDebug;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MFActionFilter implements Filter {

    private static MFActionManager manager;

    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        String url = ((HttpServletRequest) request).getRequestURI();

        if (url.endsWith(".tw")) {


            if (manager == null) {
                try {
                    manager = new MFActionManager((HttpServletRequest) request, (HttpServletResponse) response);
                    String path = MFPath.getDirFromClassLoader() + MFPath.fseparator + "mfaction.xml";
                    manager.loadConfig(path);
                } catch (Throwable ex) {
                    ex.printStackTrace();
                }
            }


            try {
                manager.updateState((HttpServletRequest) request, (HttpServletResponse) response);
                manager.runAction(url);
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
            return;
        } else
            chain.doFilter(request, response);
        ;

    }

    public void init(FilterConfig config) throws ServletException {
        MFDebug.println("启动后台Action动作过滤器服务...");
    }

}